package com.vhdadw.service.serciveImpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vhdadw.controller.request.TrafficPageRequest;
//import com.vhdadw.controller.request.UseTrafficRequest;
import com.vhdadw.enums.EventMessageType;
import com.vhdadw.interceptor.LoginInterceptor;
import com.vhdadw.manager.TrafficManager;
import com.vhdadw.model.EventMessage;
import com.vhdadw.model.TrafficDO;
import com.vhdadw.service.TrafficService;
import com.vhdadw.utils.JsonData;
import com.vhdadw.utils.JsonUtil;
import com.vhdadw.vo.ProductVO;
import com.vhdadw.vo.TrafficVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TrafficServiceImpl implements TrafficService {

    @Autowired
    TrafficManager trafficManager;


    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void handleTrafficMessage(EventMessage eventMessage) {

        String messageType = eventMessage.getEventMessageType();

        if (EventMessageType.PRODUCT_ORDER_PAY.name().equalsIgnoreCase(messageType)) {

            //订单已支付 新增流量包
            String content = eventMessage.getContent();
            Map<String, Object> orderInfoMap = JsonUtil.json2Obj(content, Map.class);

            //还原订单商品信息
            Long accountNo = (Long) orderInfoMap.get("accountNo");
            String outTradeNo = (String) orderInfoMap.get("outTradeNo");
            Integer buyNum = (Integer) orderInfoMap.get("buyNum");
            String productStr = (String) orderInfoMap.get("product");
            ProductVO productVO = JsonUtil.json2Obj(productStr,ProductVO.class);
            log.info("商品信息：{}",productVO);

            //流量包有效期
            LocalDateTime expiredDateTime = LocalDateTime.now().plusDays(productVO.getValidDay());
            Date date = Date.from(expiredDateTime.atZone(ZoneId.systemDefault()).toInstant());

            //构建流量包对象
            TrafficDO trafficDO = TrafficDO.builder()
                    .accountNo(accountNo)
                    .dayLimit(productVO.getDayTimes() * buyNum)
                    .dayUsed(0)
                    .totalLimit(productVO.getTotalTimes())
                    .pluginType(productVO.getPluginType())
                    .level(productVO.getLevel())
                    .productId(productVO.getId())
                    .outTradeNo(outTradeNo)
                    .expiredDate(date).build();

            int rows = trafficManager.add(trafficDO);
            log.info("消费消息-新增流量包：rows={},{}",rows,trafficDO);
        }

    }

    @Override
    public Map<String, Object> pageAvailable(TrafficPageRequest request) {

        Long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();

        IPage<TrafficDO> trafficDOIPage = trafficManager.pageAvailable(request.getPage(), request.getSize(), accountNo);
        System.out.println("在这");
        List<TrafficDO> records = trafficDOIPage.getRecords();
        List<TrafficVO> trafficVOList = records.stream().map(this::beanProcess).collect(Collectors.toList());

        Map<String, Object> map = new HashMap<>();
        map.put("total_records", trafficDOIPage.getTotal());
        map.put("total_page", trafficDOIPage.getPages());
        map.put("current_data", trafficVOList);

        return map;
    }

    @Override
    public TrafficVO detail(Long trafficId) {

        Long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();

        TrafficDO trafficDO = trafficManager.findByIdAndAccountNo(trafficId, accountNo);
        TrafficVO trafficVO = new TrafficVO();
        BeanUtils.copyProperties(trafficDO, trafficVO);

        return trafficVO;
    }

//    @Override
//    public boolean deleteExpireTraffic() {
//        return trafficManager.deleteExpireTraffic();
//    }

//    @Override
//    public JsonData reduce(UseTrafficRequest useTrafficRequest) {
//        return null;
//    }


    private TrafficVO beanProcess(TrafficDO trafficDO) {
        TrafficVO trafficVO = new TrafficVO();
        BeanUtils.copyProperties(trafficDO, trafficVO);
        return trafficVO;
    }

}
